<template>
  <div class="app-container">
    <!-- 课程信息表单 todo -->
    <el-form ref="courseForm" :rules="rules" :model="courseInfo">
      <el-form-item label="课程标题" prop="title">
        <el-input
          v-model="courseInfo.title"
          placeholder="请输入课程标题"
        ></el-input>
      </el-form-item>
      <el-form-item label="教师姓名:" prop="teacherId">
        <el-select v-model="courseInfo.teacherId">
          <el-option
            v-for="teacher in teacherList"
            placeholder="请选择"
            :key="teacher.id"
            :label="teacher.name"
            :value="teacher.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <div class="subjectSelect">
        <el-form-item label="课程分类:" prop="subjectParentId">
          <el-select
            v-model="courseInfo.subjectParentId"
            placeholder="请选择"
            @change="subjectChanged"
          >
            <el-option
              :key="subject.id"
              v-for="subject in subjectList"
              :label="subject.title"
              :value="subject.id"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="二级分类:" prop="subjectId">
          <el-select v-model="courseInfo.subjectId" placeholder="请选择">
            <el-option
              :key="subject.id"
              v-for="subject in subjectTwoList"
              :label="subject.title"
              :value="subject.id"
            ></el-option>
          </el-select>
        </el-form-item>
      </div>
      <el-form-item label="总课时数:" prop="lessonNum">
        <el-input-number
          v-model="courseInfo.lessonNum"
          :min="0"
          placeholder="填写总课时数"
        ></el-input-number>
      </el-form-item>
      <el-form-item label="课程简介:" prop="description">
        <Tinymce :height="300" v-model="courseInfo.description"></Tinymce>
      </el-form-item>
      <el-form-item label="课程封面">
        <el-upload
          class="avatar-uploader"
          action="http://localhost:9110/aliyun-oss/admin/aliyun/file/upload"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
          :on-error="handleCoverError"
        >
          <img v-if="courseInfo.cover" :src="courseInfo.cover" class="avatar" />
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>
      <el-form-item label="课程价格:" prop="price">
        <el-input-number
          v-model="courseInfo.price"
          :min="0"
          placeholder="课程价格"
        ></el-input-number>
      </el-form-item>
    </el-form>
    <!-- 课程信息表单 -->

    <div style="text-align:center;">
      <el-button
        type="primary"
        :disabled="saveBtnDisabled"
        @click="saveAndNext('courseForm')"
        >下一步</el-button
      >
      <el-button type="primary" @click="resetForm('courseForm')"
        >重置</el-button
      >
    </div>
  </div>
</template>

<script>
import { Message } from "element-ui";
import courseApi from "@/api/course";
import teacher from "../../../api/teacher";
import subject from "../../../api/subject";
// import TinyMecVue from "../../../components/Tinymce/TinyMec.vue";
// import Tinymce from "@/components/Tinymce";
import Tinymce from "@/components/Tinymce";
export default {
  components: { Tinymce }, //富文本编辑器组件
  created() {
    this.initTeacherList();
    //courseId 来源于路由
    if (this.$route.name === "CourseInfoEdit") {
      this.$parent.courseId = this.$route.params.id;
    }

    //courseId 来源于父组件
    if (this.$parent.courseId) {
      this.fetchCourseInfoById(this.$parent.courseId);
    } else {
      //新增，只渲染一及类别
      this.initSubjectList();
    }
  },
  data() {
    return {
      subjectTwoList: [],
      subjectList: [],
      teacherList: [],
      saveBtnDisabled: false,
      courseInfo: {
        price: 0,
        lessonNum: 0,
        teacherId: "",
        subjectId: "",
        subjectParentId: "",
        cover: "",
        description: "",
      }, //课程基本信息
      rules: {
        description: [{ required: true, message: "请输入", trigger: "blur" }],
        title: [{ required: true, message: "请输入", trigger: "blur" }],
        lessonNum: [{ required: true, message: "请选择", trigger: "change" }],
        price: [{ required: true, message: "请选择", trigger: "change" }],
        teacherId: [{ required: true, message: "请选择", trigger: "blur" }],
        subjectId: [{ required: true, message: "请选择", trigger: "blur" }],
        subjectParentId: [
          { required: true, message: "请选择", trigger: "blur" },
        ],
      },
    };
  },
  methods: {
    /**
     * 根据id查询课程信息
     */
    fetchCourseInfoById(id) {
      courseApi.getCourseInfoById(id).then((resp) => {
        if (resp) {
          //课程类别渲染
          subject.getSubjectTreeList().then((resp) => {
            this.subjectList = resp.data.items;
            //判断this.subjectList 是哪一个类别
            this.subjectList.forEach((subject) => {
              if (subject.id === this.courseInfo.subjectParentId) {
                this.subjectTwoList = subject.children;
              }
            });
          });

          this.courseInfo = resp.data.item;
        }
      });
    },
    handleCoverError() {
      this.$message.error("文件上传失败！");
    },
    handleAvatarSuccess(res, file) {
      if (res.success) {
        this.courseInfo.cover = res.data.url;
        this.$forceUpdate();
      } else {
        this.$message.error("文件上传失败！");
      }
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
    subjectChanged(val) {
      this.subjectList.forEach((subject) => {
        if (subject.id === val) {
          this.courseInfo.subjectId = "";
          this.subjectTwoList = subject.children;
          // console.log(this.subjectTwoList);
        }
      });
    },
    initSubjectList() {
      subject.getSubjectTreeList().then((resp) => {
        if (resp) {
          this.subjectList = resp.data.items;
        }
      });
    },
    /**
     * 讲师列表
     */
    initTeacherList() {
      teacher.list().then((resp) => {
        if (resp) {
          this.teacherList = resp.data.items;
          console.log(this.teacherList);
        }
      });
    },
    /**
     * 保存课程信息
     */
    saveDate() {
      courseApi.saveCourseInfo(this.courseInfo).then((resp) => {
        this.$message.success(resp.message);
        this.$parent.courseId = resp.data.courseId; //获取courseId
        this.$parent.active = 1; // 访问父组件成员 $parent
      });
    },

    updateData() {
      courseApi.updateCourseInfoById(this.courseInfo).then((resp) => {
        this.$parent.active = 1;
      });
    },
    /**
     * 验证表单
     */
    saveAndNext(courseForm) {
      this.$refs[courseForm].validate((valid) => {
        if (valid) {
          // this.saveBtnDisabled = true;
          if (!this.$parent.courseId) {
            this.saveDate();
          } else {
            this.updateData();
          }
        } else {
          // this.$message.warn("请输入必填项");
          Message.warning("输入必填项");
          return false;
        }
      });
    },

    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
  },
};
</script>

<style>
.subjectSelect {
  justify-content: flex-start;
  display: flex;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
